<template>
  <div class="app-container">

    <el-button type="primary" @click="handleAddRole">新增</el-button>
    <el-select v-model="adType" placeholder="请选择" @change="adTypeChange">
      <el-option v-for="item in options" :key="item.type" :label="item.name" :value="item.type">
      </el-option>
    </el-select>

    <div style="height:650px">
      <el-table :data="rolesList" v-loading='loading' style="width: 100%;margin-top:30px;" border>
        <el-table-column label="ID">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="链接">
          <template slot-scope="scope">
            {{ scope.row.link }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="图标">
          <template slot-scope="scope">
            <img :src="scope.row.url" :alt="scope.row.url" style="width: 100px; height: 50px;" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="展示位">
          <template slot-scope="scope">
            {{ scope.row.position==1?"首页":scope.row.position==2?"中部":"尾部" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="开始实际">
          <template slot-scope="scope">
            {{ scope.row.startTime }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="结束时间">
          <template slot-scope="scope">
            {{ scope.row.endTime }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否展示">
          <template slot-scope="scope">
            {{ scope.row.enabled?'是':'否' }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="添加时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-popconfirm title="是否删除" @confirm='handleDelete(scope.row)'>
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 添加对话框 -->
    <el-dialog :visible.sync="createDialogVisible" @close="handleCancel" :close-on-click-modal="false" :title="isAddOrUpdata?'新增广告':'修改广告'">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>
        <el-form-item label="上传图片" prop="url">
          <el-upload :headers="headers" :limit="1" :data='{dirName:""}' list-type="picture-card" ref="uploadIMG" :file-list="fileList" :on-error="fileError" :on-remove="handleRemove" :action="uploadPath" :auto-upload="false" :on-success="handleAvatarSuccess" :on-change="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告类型：">
          <el-select v-model="ruleForm.type" placeholder="请选择">
            <el-option v-for="item in options" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="广告标题：" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>

        <el-form-item label="广告链接：" prop="link">
          <el-input v-model="ruleForm.link" />
        </el-form-item>

        <el-form-item label="广告位置：" prop="position">
          <el-select v-model="ruleForm.position" placeholder="请选择">
            <el-option v-for="item in positionList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="广告开始时间：" required>
          <el-col :span="6">
            <el-form-item prop="startTimeDate">
              <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择开始日期" v-model="ruleForm.startTimeDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="width:10px;">-</el-col>
          <el-col :span="5">
            <el-form-item prop="startTimeShijian">
              <el-time-picker placeholder="选择开始时间" format="HH:mm:ss" value-format="HH:mm:ss" v-model="ruleForm.startTimeShijian" style="width: 100%;"></el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="广告结束时间：" required>
          <el-col :span="6">
            <el-form-item prop="endTimeDate">
              <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择结束日期" v-model="ruleForm.endTimeDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="width:10px;">-</el-col>
          <el-col :span="5">
            <el-form-item prop="endTimeShijian">
              <el-time-picker placeholder="选择结束时间" format="HH:mm:ss" value-format="HH:mm:ss" v-model="ruleForm.endTimeShijian" style="width: 100%;"></el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="排序：">
          <el-input-number :min=0 v-model="ruleForm.sortNum" />
        </el-form-item>
        <el-form-item label="是否展示：" prop="aliOss">
          <el-switch v-model="ruleForm.enabled"></el-switch>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <el-pagination background layout="prev, pager, next,sizes,total" :total='total' @current-change='current_change' @size-change='size_change' style="text-align: center; margin-top: 60px;" :page-sizes="[10, 50, 100, 1000]">
    </el-pagination>

  </div>
</template>

<script>
import api from '@/api/Advertising'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'Advertising',
  data() {
    return {
      adType: 1,
      options: [
        {
          type: 1,
          name: '版本库广告'
        },
        {
          type: 2,
          name: '官网广告'
        },
        {
          type: 3,
          name: '藏宝阁广告'
        },
        {
          type: 4,
          name: '素材网广告'
        }
      ],
      isImgCheak: false,
      isAddOrUpdata: true, // true新增false修改
      createDialogVisible: false,
      uploadPath: uploadPath,
      rolesList: [],
      fileList: [],
      total: 0,
      limit: '',
      page: '',
      pages: '',
      loading: false,
      positionList: [
        { id: 1, name: '首页' },
        { id: 2, name: '中部' },
        { id: 3, name: '底部' }
      ],
      ruleForm: {
        name: '',
        url: '',
        link: '',
        startTimeDate: '',
        startTimeShijian: '',
        startTime: '',
        endTimeDate: '',
        endTimeShijian: '',
        endTime: '',
        position: '',
        enabled: false,
        type: 1,
        sortNum: 0
      },
      rules: {
        name: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
        url: [
          {
            required: true,
            message: '请填上传正确格式的缩略图',
            trigger: 'change'
          }
        ],
        position: [
          { required: true, message: '请选择展示的位置', trigger: 'change' }
        ],
        link: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
        startTimeDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        startTimeShijian: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTimeDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        endTimeShijian: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    adTypeChange() {
      this.getList()
    },
    handleRemove() {
      // 移除图片
      this.ruleForm.url = ''
    },

    beforeAvatarUpload(file) {
      // 图片改变
      this.isImgCheak = true
      var isJPG = false
      if (
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/png' ||
        file.raw.type === 'image/gif'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return
      }
      this.ruleForm.url = URL.createObjectURL(file.raw)

      return isJPG && isLt2M
    },

    handleAvatarSuccess(res, file) {
      // 上传成功
      if (res.errno == 0) {
        this.ruleForm.url = res.data.url
        if (this.isAddOrUpdata) {
          this.Create(this.ruleForm)
        } else {
          this.update(this.ruleForm)
        }
      }
    },
    fileError(err, file, fileList) {
      // 上传出错
      this.ruleForm.url = ''
      this.$message({
        message: '上传出错',
        type: 'warning'
      })
    },

    handleAddRole() {
      // 新增对话框
      this.isAddOrUpdata = true
      this.createDialogVisible = true
    },
    handlePublish() {
      // 新增图片
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.ruleForm.startTime =
            this.ruleForm.startTimeDate + ' ' + this.ruleForm.startTimeShijian
          this.ruleForm.endTime =
            this.ruleForm.endTimeDate + ' ' + this.ruleForm.endTimeShijian
          if (!this.isImgCheak) {
            if (this.isAddOrUpdata) {
              this.Create(this.ruleForm)
            } else {
              this.update(this.ruleForm)
            }
          } else {
            this.$refs.uploadIMG.submit()
          }
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },
    handleCancel() {
      this.createDialogVisible = false
      this.ruleForm.name = ''
      this.ruleForm.url = ''
      this.ruleForm.link = ''
      this.ruleForm.startTimeDate = ''
      this.ruleForm.startTimeShijian = ''
      this.ruleForm.endTimeDate = ''
      this.ruleForm.endTimeShijian = ''
      this.ruleForm.position = ''
      this.ruleForm.enabled = false
      this.fileList = []
    },
    handleEdit(e) {
      var s = e.startTime.split(' ')
      var end = e.endTime.split(' ')
      this.isAddOrUpdata = false
      this.ruleForm.type = e.type
      this.ruleForm.name = e.name
      this.ruleForm.url = e.url
      this.ruleForm.link = e.link
      this.ruleForm.startTimeDate = s[0]
      this.ruleForm.startTimeShijian = s[1]
      this.ruleForm.endTimeDate = end[0]
      this.ruleForm.endTimeShijian = end[1]
      this.ruleForm.position = e.position
      this.ruleForm.enabled = e.enabled
      this.ruleForm.id = e.id
      this.fileList.push({
        url: e.url
      })
      this.createDialogVisible = true
    },
    handleDelete(e) {
      api.Delete(e).then((res) => {
        if (res.data.errno == 0) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }
      })
    },
    current_change(e) {
      this.page = e
      this.getList()
    },
    size_change(e) {
      this.limit = e
      this.getList()
    },
    Create(e) {
      this.loading = true
      api
        .create(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.getList()
            this.createDialogVisible = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    },
    update(e) {
      this.loading = true
      api
        .update(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getList()
            this.createDialogVisible = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    },
    getList() {
      this.loading = true
      api
        .list({ type: this.adType })
        .then((res) => {
          if (res.data.errno == 0) {
            this.rolesList = res.data.data.list
            this.total = res.data.data.list.length
            this.page = res.data.data.page
            this.pages = res.data.data.pages
            this.total = res.data.data.total
            this.limit = res.data.data.limit
            this.loading = false
          }
        })
        .catch(() => {
          this.Loading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
</style>